package com.hzsai.nettylearn.server;

import com.hzsai.nettylearn.util.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

/**
 * hzsai 2019/11/13
 * usage: 请求处理handler，实现Runnable接口
 **/
public class TimeServerHandler implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(TimeServerHandler.class);

    private Socket socket;

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {

        // 客户端接入处理逻辑
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            PrintWriter   out = new PrintWriter(this.socket.getOutputStream());

            // socket.setKeepAlive(true);
            String reciveMsg;

            while (true) {
                /**
                 * bug1:
                 * 这里有坑，在模拟测试发送数据的时候，如果代码里使用readline的话，会一直等待一个'\n'符号
                 * 在不细心的情况下，很容易忽略而发生奇怪的问题！！！
                 */
                reciveMsg = in.readLine();
                if (reciveMsg == null) break;
                logger.info(DateTimeUtil.getDate() + "Server：Client info -> {}",
                        socket.getInetAddress().getHostAddress() + ":" + String.valueOf(socket.getPort()));
                //reciveMsg = in.readLine(); // BUG1: 线程在用完第一次之后，就报错了recv failed.
                if (socket.isClosed()) break;
                if (reciveMsg == null) continue;

                logger.info(DateTimeUtil.getDate() + "Server：Messages from 【{}】：{}",
                        socket.getInetAddress().getHostAddress() + ":" + String.valueOf(socket.getPort()), reciveMsg);
                out.println("Recived: " + reciveMsg);

                //flush the stream
                out.flush();
            }
            // bug2:
            // 确保链接是关闭的，否则会浪费socket资源
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
